package com.fram.service.api.v1.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fram.bean.api.message.request.MessageDeleteRequest;
import com.fram.bean.api.message.request.MessageReadRequest;
import com.fram.bean.api.message.request.MessageSearchRequest;
import com.fram.bean.api.message.response.MessageSearchResponse;
import com.fram.bean.sys.PageBean;
import com.fram.common.canstant.ErrCode;
import com.fram.common.canstant.PublicConstant;
import com.fram.common.exception.ProException;
import com.fram.common.exception.ProValiDataException;
import com.fram.entity.MessageReadDel;
import com.fram.mapper.MessageDataMapper;
import com.fram.mapper.MessageReadDelMapper;
import com.fram.service.api.v1.MessageService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * @作者： 陳曉鬆 @时间： 2020年6月2日 - 上午10:19:39 @description：->
 */
@Service("messageService")
public class MessageServiceImpl implements MessageService {

	@Autowired
	private MessageDataMapper messageDataMapper;
	@Autowired
	private MessageReadDelMapper messageReadDelMapper;

	@Override
	public PageInfo<MessageSearchResponse> list(PageBean<MessageSearchRequest> request) throws ProException {
		PageHelper.startPage(request.getPageNum(), request.getPageSize());
		List<MessageSearchResponse> list = messageDataMapper.selectMyMessage(request.getParam());
		if (list == null || list.size() == 0) {
			throw new ProValiDataException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		return new PageInfo<>(list);
	}

	@Override
	public void read(MessageReadRequest request, Long userId) throws ProException {
		if (request.getIsRead() != PublicConstant.MESSAGE_READ_0 && request.getIsRead() != PublicConstant.MESSAGE_READ_1) {
			throw new ProValiDataException(ErrCode.ERR_PARAMETER.getReturnCode(), ErrCode.ERR_PARAMETER.getReturnMsg());
		}
		List<MessageReadDel> record = new ArrayList<MessageReadDel>();
		for (Long id : request.getMessageIds()) {
			MessageReadDel read = new MessageReadDel();
			read.setMessageId(id);
			read.setUserId(userId);
			read.setIsRead(request.getIsRead());
			record.add(read);
		}
		if (messageReadDelMapper.insertList(record) <= 0) {
			throw new ProValiDataException(ErrCode.FAIL.getReturnCode(), "标记消息为已读失败");
		}
	}

	@Override
	public void delete(MessageDeleteRequest request, Long userId) throws ProException {
		List<MessageReadDel> record = new ArrayList<MessageReadDel>();
		for (Long id : request.getMessageIds()) {
			MessageReadDel read = new MessageReadDel();
			read.setMessageId(id);
			read.setUserId(userId);
			read.setIsRead(PublicConstant.MESSAGE_READ_1);
			read.setIsDelete(0);// 删除
			record.add(read);
		}
		if (messageReadDelMapper.insertList(record) <= 0) {
			throw new ProValiDataException(ErrCode.FAIL.getReturnCode(), "消息删除失败");
		}
	}

}
